import type { Grade } from '@/types/grade';
import { showNotification } from '@/utils/notify';
import request from '@/utils/request';
import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useGradeStore = defineStore('grade', () => {
    const grades = ref<Grade[]>([]);
    const myGrades = ref<Grade[]>([]);

    // 分页相关状态
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    const fetchMyGrades = async () => {
        try {
            const { data } = await request.get<{ code: number; message: string; data: { records: Grade[]; total: number } }>(
                `/api/grades/page/student?current=${currentPage.value}&size=${pageSize.value}`
            );
            if (data) {
                myGrades.value = data.records;
                total.value = data.total;
            }
        } catch (error) {
            console.error('获取成绩数据失败:', error);
        }
    };

    const saveOrUpdateGrade = async (grade: Grade) => {
        try {
            const { data } = await request.post<{ code: number; message: string; data: object }>('/api/grades/add', grade);
            if (data) {
                showNotification('成绩增改成功');
                await fetchMyGrades(); // 增改后重新获取数据
            }
        } catch (error) {
            console.error('成绩增改失败:', error);
        }
    };

    const deleteGrade = async (id: number) => {
        try {
            await request.delete(`/api/grades/${id}`);
            showNotification('成绩删除成功');
            await fetchMyGrades(); // 删除后重新获取数据
        } catch (error) {
            console.error('成绩删除失败:', error);
        }
    };

    // 切换页码
    const changePage = async (page: number) => {
        currentPage.value = page;
        await fetchMyGrades();
    };

    // 改变每页数量
    const changePageSize = async (size: number) => {
        pageSize.value = size;
        currentPage.value = 1;
        await fetchMyGrades();
    };

    return {
        grades,
        myGrades,
        currentPage,
        pageSize,
        total,
        fetchMyGrades,
        saveOrUpdateGrade,
        deleteGrade,
        changePage,
        changePageSize
    };
});
    